from flask import Flask, url_for, jsonify, request, send_from_directory
from json2html import *
import json
import numpy as np
import re
app = Flask(__name__)
devices = {'No Device Connected':"<b><font color=\"#FF0000\">%s</font></b>"%'No Device Connected'}
global html_col1, html_col2, html_col3, template
html_col1 = json2html.convert(json = devices, escape=False)
html_col2 = json2html.convert(json = devices, escape=False)
html_col3 = json2html.convert(json = devices, escape=False)

with open('template.html','r',encoding = "utf-8") as f:
    template = f.read()

def process(dic):
    global html_col1, html_col2, html_col3, template
    ID = dic['hostname']

    # 加粗ip地址
    dic['ip'] = "<b><font color=\"#FF0000\">%s</font></b>"%dic['ip']

    # highlight 百分比
    def color_percent(o_string):
        res = re.findall(r'[\d\.\d]+', o_string)
        percent = float(res[0])
        if percent > 80.0:
            mod = "<b><font color=\"#FF0000\">%s</font></b>"%o_string
        elif percent > 50.0:
            mod = "<b><font color=\"#FFD700\">%s</font></b>"%o_string
        elif percent > 30.0:
            mod = "<b><font color=\"#00FF00\">%s</font></b>"%o_string
        else:
            mod = "<b><font color=\"#00FFFF\">%s</font></b>"%o_string
        return mod
    # deep in
    def deep_in(dic):
        for key in dic:
            if '%' in dic[key]:
                dic[key] = color_percent(dic[key])
            if isinstance(dic[key],dict):
                dic[key] = deep_in(dic[key])
        return dic
        
    dic = deep_in(dic)



    devices[ID] = dic
    if 'No Device Connected' in devices:
        devices.pop('No Device Connected')



    device_col1 = {}
    device_col2 = {}
    dev_list = list(devices.keys())
    n_dev = len(dev_list)
    for i in range(int(n_dev//2)):
        dev_key = dev_list[i]
        device_col1[dev_key] = devices[dev_key]

    for i in range(int(n_dev//2), n_dev):
        dev_key = dev_list[i]
        device_col2[dev_key] = devices[dev_key]

    html_col1 = json2html.convert(json = device_col1, escape=False)
    html_col2 = json2html.convert(json = device_col2, escape=False)
    device_col3 = {}
    for i in range(n_dev):
        dev_key = dev_list[i]
        d = devices[dev_key]
        device_col3[dev_key] = 'IP: %s, CPU: %s'%(d['ip'], d['CPU利用率'])
    html_col3 = json2html.convert(json = device_col3, escape=False)

    return

@app.route('/')
def index():
    global html_col1, html_col2, html_col3, template
    res = template.replace('FILL_EVERYTHING_HERE_COL1', html_col1)
    res = res.replace('FILL_EVERYTHING_HERE_COL2', html_col2)
    res = res.replace('FILL_EVERYTHING_HERE_COL3', html_col3)
    res = res.replace('FILL_2233_HERE', '3')
    TEXTURE = np.random.randint(low=0,high=157)
    print('TEXTURE', TEXTURE)
    res = res.replace('FILL_TEXTURE_HERE', str(TEXTURE))
    return res


@app.route('/server')
def server():
    global html_col1, html_col2, html_col3, template
    res = template.replace('FILL_EVERYTHING_HERE_COL1', html_col1)
    res = res.replace('FILL_EVERYTHING_HERE_COL2', html_col2)
    res = res.replace('FILL_EVERYTHING_HERE_COL3', html_col3)
    res = res.replace('FILL_2233_HERE', '3')
    TEXTURE = 0
    print('TEXTURE', TEXTURE)
    res = res.replace('FILL_TEXTURE_HERE', str(TEXTURE))
    return res


@app.route('/h5json')
def h5json():
    global html
    return html

@app.route("/assets/<path:path>")
def static_dir(path):
    return send_from_directory("assets", path)

@app.route('/login')
def login():
    with open('template.html','r',encoding = "utf-8") as f:
        return f.read()

@app.route('/user',methods=['GET', 'POST'])
def profile():
    info = request.data
    info = info.decode('utf-8')
    res = json.loads(info)
    process(res)
    return ''

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('server'))
    print(url_for('h5json'))
    print(url_for('profile'))
    print(url_for('login', next='/'))

app.run(host='0.0.0.0',port=5000)